package cn.yili12.business.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.SecureUtil;
import cn.yili12.business.dto.LoginDTO;
import cn.yili12.business.dto.LoginResultDTO;
import cn.yili12.business.dto.RegisterDTO;
import cn.yili12.business.entity.UserDb;
import cn.yili12.business.service.OrganizeService;
import cn.yili12.business.service.UserService;
import cn.yili12.business.vo.Result;
import cn.yili12.common.util.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@RestController
@RequestMapping("/anonymous")
@Api(value = "匿名操作接口(登录、注册)")
@Slf4j
public class AnonymousController {
    @Autowired
    private UserService service;
    @Autowired
    private OrganizeService organizeService;

    @PostMapping("/login")
    @ApiOperation("登录操作")
    public Result handler(@Valid LoginDTO loginDTO) {
        UserDb user = service.getByPhone(loginDTO.getUsername());
        if (user == null) {
            return Result.fail("用户不存在");
        }
        String pwd = SecureUtil.md5(loginDTO.getPassword());
        if (!pwd.equals(user.getPassword())) {
            return Result.fail("用户名或者密码错误");
        }
        String jwt = JwtUtil.sign(String.valueOf(user.getId()), String.valueOf(user.getOrgId()), user.getPassword());
        log.info("用户{}登录成功，jwt={}", new Object[]{user.getPhone(), jwt});
        return Result.success("登录成功", new LoginResultDTO(String.valueOf(user.getId()), user.getPhone(), user.getName(), jwt));
    }

    @PostMapping("/register")
    @ApiOperation("注册操作")
    public Result register(@Valid RegisterDTO registerDTO) {
        UserDb byPhone = service.getByPhone(registerDTO.getPhone());
        if (byPhone != null) {
            return Result.fail("电话号码已经注册");
        }
        try {
            if (null == organizeService.get(Long.valueOf(registerDTO.getOrgId()))) {
                return Result.fail("组织不存在");
            }
            UserDb userDb = new UserDb();
            BeanUtil.copyProperties(registerDTO, userDb);
            userDb.setPassword(SecureUtil.md5(registerDTO.getPassword()));
            service.save(userDb);
            return Result.success("注册成功", registerDTO);
        } catch (Exception e) {
            log.error("注册报错", e);
            return Result.fail("注册失败");
        }
    }
}
